<template>
    <div class="login">
        <el-form label-width="100px" class="loginForm" :model="loginForm" :rules="rules" ref="loginFormRef">
            <el-form-item label="用户名" prop="username">
                <el-input type="text" autocomplete="off" v-model="loginForm.username" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input type="text" autocomplete="off" v-model="loginForm.password" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="login(loginFormRef)">登录</el-button>
                <el-button>重置</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router'
import { reactive, ref } from 'vue'
import { ElMessage, FormInstance, FormRules } from "element-plus";
import {userlogin} from '../request/api'
import {useStore} from 'vuex';
let router = useRouter()
let store=useStore()
store.dispatch('changeUserAction')
let loginFormRef = ref<FormInstance>()
let loginForm = ref({
    username: '',
    password: ''
})
let rules = reactive<FormRules>({
    username: [
        { required: true, message: "请输入用户名", trigger: "blur" },
        { min: 2, max: 8, message: "长度2-8之间", trigger: "blur" },
    ],
    password: [
        { required: true, message: "请输入密码", trigger: "blur" },
        { min: 6, max: 16, message: "长度6-16之间", trigger: "blur" },
    ],
});
let login=(formEl:FormInstance|undefined)=>{
    if(formEl){
        formEl.validate((val)=>{
            // console.log(val);
            if(val){
                // router.push('/index')
                userlogin(loginForm.value).then((res:any)=>{
                    // console.log(res);
                    if(res.data.code==200){
                        console.log(res);
                        ElMessage.success(res.data.msg)
                        store.dispatch('changeUserAction',res.data.list)
                        router.push('/home')
                    }else{
                        ElMessage.error(res.data.msg)
                    }
                })
            }
        })
    }
}
</script>

<style scoped lang="less">
.login {
    width: 100vw;
    height: 100vh;

    .loginForm {
        position: absolute;
        width: 400px;
        height: 350px;
        top: 50%;
        left: 50%;
        margin: -175px 0 0 -175px;
    }
}
</style>